package com.ruleengine.router.manager;

import org.apache.log4j.Logger;

import com.ruleengine.router.IRouter;
import com.ruleengine.router.impl.AbstractRouter;
import com.ybt.configration.IYBTConfigration;
import com.ybt.configration.YBTConfigration;

public class RuleEngineRouterManager {
    private static Logger logger = Logger
            .getLogger(RuleEngineRouterManager.class);
    private AbstractRouter router;
    private volatile static RuleEngineRouterManager manager;

    private RuleEngineRouterManager() {
        String rp = YBTConfigration.getInstance().getProperty(
                IYBTConfigration.WORKFLOW_ROUTER);
        if(logger.isDebugEnabled()){
            logger.debug("initialize rule engine routers...");
        }
        rp += ",com.ruleengine.router.impl.ErrorRouter";
        String[] routers = rp.split(",");
        for (int i=routers.length-1; i>0; i--) {
            //初始化路由器链路
            try {
                String r = routers[i].trim();
                if("".equals(r)){
                    continue;
                }
                if(logger.isDebugEnabled()){
                    logger.debug("initialize : "+r);
                }
                // 初始化路由器
                Class c = Class.forName(r);
                AbstractRouter t = (AbstractRouter) c.newInstance();
                
                //设置路由器链路
                t.setRouter(router);
                router = t;
                
            } catch (Exception e) {
                throw new RuntimeException(
                        "initialize rule engine routers error :" + rp, e);
            }
        }
    }

    public static RuleEngineRouterManager getInstance() {
        if (manager == null) {
            synchronized (RuleEngineRouterManager.class) {
                if (manager == null) {
                    manager = new RuleEngineRouterManager();
                }
            }
        }
        return manager;
    }

    public IRouter getRuleEngineRouter() {
        return router;
    }
}
